package com.ifcar.app.activity;

import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;

import com.ifcar.app.activity.common.CommentFragment;
import com.ifcar.app.activity.newspage.NewsCommentFragment;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.rss.GetComments;
import com.ifcar.app.util.CollectArticleAdapter;
import com.ifcar.app.util.CollectPicturesAdapter;
import com.ifcar.app.util.CollectUtil;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.activity.R;


public class CollectActivity extends BaseActivity {
	
	private LinearLayout collect_layout_bg;
	private TextView empty_text;
	private TextView main_text;
	private ListView collectList;
	private GridView collectGridView;
	private CollectPicturesAdapter pgridadapter;
	private CollectArticleAdapter articleAdapter;
	
	private TextView top_article;
	private TextView top_picture;
	private TextView top_comment;
	
	private List<Map<String, Object>> collectData;
	private CollectUtil cu;
	
	private ImageView imageBg;	
	private Animation animation; 
	private int collectType = CollectUtil.COLLECT_ARTICLE;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.collect_main);
		
		hideIcon();
		findViews();
		updateViewContent();
		setListViewData();
		setMenu();
	
		collectGridView.setOnItemClickListener(gridViewClistener);
		collectList.setOnItemClickListener(listViewClickListener);
	}

	private void findViews(){
		
		collect_layout_bg = (LinearLayout)findViewById(R.id.collect_layout_bg);
		empty_text = (TextView)findViewById(R.id.empty_text);
		main_text = (TextView)findViewById(R.id.top_main_text);
		
		top_article = (TextView)findViewById(R.id.collect_article);
		top_article.setTag("1");
		old = top_article;
		old.setEnabled(false);
		old.setSelected(true);
		top_picture = (TextView)findViewById(R.id.collect_pictures);
		top_picture.setTag("2");
		top_comment = (TextView)findViewById(R.id.collect_comment);
		top_comment.setTag("3");
		
		imageBg = (ImageView)findViewById(R.id.slider_image);
		FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)imageBg.getLayoutParams();
		lp.width = screenwidth / 3;
		
		collectList = (ListView)findViewById(R.id.collect_article_list);
		collectGridView = (GridView)findViewById(R.id.collect_pictures_gridview);
	}
	private void updateViewContent(){
		main_text.setText(getResources().getString(R.string.main_title_collect));
		
		top_article.setOnClickListener(textViewListener);
		top_picture.setOnClickListener(textViewListener);
		top_comment.setOnClickListener(textViewListener);
	}
	
	private View old;
	private View.OnClickListener textViewListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			sliderBg(v); // 滑动效果

			if(collectData.size()==0)
				empty_text.setVisibility(View.VISIBLE);
			else
				empty_text.setVisibility(View.GONE);
			
			switch (v.getId()) {
			case R.id.collect_article: // 文章
				collectType = CollectUtil.COLLECT_ARTICLE;
				setListViewData() ;
				break;
			case R.id.collect_pictures: // 图片
				collectType = CollectUtil.COLLECT_PICTURES;				
				setPicViewData();
				break;
			case R.id.collect_comment: // 跟贴
				collectType = CollectUtil.COLLECT_COMMENT;				
				setListViewData() ;
				break;
			}
		}
	};
	
	private void setListViewData() {		
		cu = new CollectUtil(CollectActivity.this);
		collectData = cu.getCollectObjects(collectType);
		
		articleAdapter = new CollectArticleAdapter(CollectActivity.this, collectData, true);
		collectList.setAdapter(articleAdapter);
		
		if(collectData.size()==0)
			empty_text.setVisibility(View.VISIBLE);
		else
			empty_text.setVisibility(View.GONE);
		setObjVisibility();
	}
	
	private void setPicViewData(){
		collectData = cu.getCollectObjects(collectType);
		if(collectData.size()==0){
		    collectGridView.setBackgroundDrawable(null);
			empty_text.setVisibility(View.VISIBLE);
		}else{
			empty_text.setVisibility(View.GONE);
			collectGridView.setBackgroundResource(R.drawable.pictures_bg);
		}
		
		setObjVisibility();
		
		pgridadapter = new CollectPicturesAdapter(CollectActivity.this, collectData, true,null);
		collectGridView.setAdapter(pgridadapter);
	}
	
	private void setObjVisibility(){
		if(collectType==CollectUtil.COLLECT_PICTURES){
			collectList.setVisibility(View.GONE);
			collectGridView.setVisibility(View.VISIBLE);
		}else{
			collectList.setVisibility(View.VISIBLE);
			collectGridView.setVisibility(View.GONE);
		}
	}
	
	private void sliderBg(final View v) {
		
		int num = Integer.parseInt(v.getTag().toString()) - Integer.parseInt(old.getTag().toString());
		
		int toX = num * v.getWidth();
		int left = old.getLeft();
		
		old.setEnabled(true);
		old.setSelected(false);
		v.setEnabled(false);
		old = v;

		animation = new TranslateAnimation(left, left+toX, 0, 0);
		Interpolator intep = AnimationUtils.loadInterpolator(CollectActivity.this, android.R.anim.decelerate_interpolator);
		animation.setInterpolator(intep);
		animation.setFillAfter(true);
		animation.setAnimationListener(new AnimationListener() {			
			@Override
			public void onAnimationEnd(Animation animation) {
			    v.setSelected(true);
			}
			@Override
			public void onAnimationStart(Animation animation) {}
			@Override
			public void onAnimationRepeat(Animation animation) {}
		});
	
		animation.setDuration(200);
		imageBg.startAnimation(animation);
	}
	
	/** GridView Item click */
	private OnItemClickListener gridViewClistener = new OnItemClickListener (){

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {			
			Map<String , Object> m = collectData.get(position);
			Intent intent = new Intent(CollectActivity.this, ImageSwitcherActivity.class);
			Bundle bundle = new Bundle();
			String id = StringUtil.GetString(m.get(NewsSQLiteOpenHelper.COLLECT_OBJID));
			JSONObject obj;
			String setid = "";
			String imgsum = "";
			String channel = "";
			try {
				obj = new JSONObject(id);
				if(obj!=null){
					setid = obj.getString("setId");
					imgsum = obj.getString("num");
					channel = obj.getString("channel");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			String imgTitle = m.get(NewsSQLiteOpenHelper.COLLECT_TITLE)==null?"":StringUtil.GetString(m.get(NewsSQLiteOpenHelper.COLLECT_TITLE));
			String clientcover = m.get(NewsSQLiteOpenHelper.COLLECT_PATH)==null?"":StringUtil.GetString(m.get(NewsSQLiteOpenHelper.COLLECT_PATH));
			
			bundle.putString("setid", setid);
			bundle.putString("channel", channel);
			bundle.putString("imgsum", imgsum);
			bundle.putString("imgTitle", imgTitle);
			bundle.putString("clientcover", clientcover);
			intent.putExtras(bundle);
			startActivity(intent);
		}
	};
	
	/** ListView Item click */
	private OnItemClickListener listViewClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            if (position >= collectData.size()) {
                return;
            }
			if(collectType == CollectUtil.COLLECT_COMMENT){ // 跟贴
				Map<String , Object> m = collectData.get(position);
				String path = m.get(NewsSQLiteOpenHelper.COLLECT_PATH)==null?"":StringUtil.GetString(m.get(NewsSQLiteOpenHelper.COLLECT_PATH));
				String type = m.get(NewsSQLiteOpenHelper.COLLECT_TYPE) + "";
				if(String.valueOf(CollectUtil.COLLECT_COMMENT).equals(type)){
					JSONObject json;
					String replyBoard = "";
					String postid = "";
					String p= "";
					
					Object o = m.get(NewsSQLiteOpenHelper.COLLECT_TITLE);
					String title = null==o?"":o.toString();
					o = m.get(NewsSQLiteOpenHelper.COLLECT_OBJID);
					String comment_column_id = null==o?"0":o.toString();
					
					try {
						json = new JSONObject(path);
						if(null!=json){
							replyBoard = json.getString("replyBoard");
							postid = json.getString("postid");
							p = json.getString("p");
							
							json = new JSONObject();
							json.put(GetComments.P_TAG, p==null?"":p);
							json.put(GetColumnsInfo.POSTID_TAG, postid);
							json.put(GetColumnsInfo.REPLYBOARD_TAG, replyBoard);
						} else {
						    return;
						}
					} catch (JSONException e) {
						e.printStackTrace();
						return;
					}
	
//					Bundle bundle = new Bundle();
//					if(null!=p && p.length()>0)
//						bundle.putString(GetComments.P_TAG,p);
//					
//					bundle.putString(GetColumnsInfo.REPLYBOARD_TAG,replyBoard);
//					bundle.putString(GetColumnsInfo.POSTID_TAG,postid);
//					bundle.putString(GetColumnsInfo.TITLE_TAG,title);
//					
//					bundle.putInt(StringUtil.COMMENT_COLUMN_ID, Integer.parseInt(comment_column_id));
//					bundle.putBoolean("isCollect", true);
//	                   Intent intent = new Intent(CollectActivity.this, ShowComments.class);
//	                    intent.putExtras(bundle);
					
					Bundle bundle = new Bundle();
					bundle.putString(CommentFragment.BOARD_ID, replyBoard);
		            bundle.putString(CommentFragment.DOC_ID, postid);
		            bundle.putString(CommentFragment.DOC_TITLE, title);
		            bundle.putString(CommentFragment.COMMENT_URL, json.toString());
		            
			        Intent intent = new Intent(CollectActivity.this, NewsPage.class);
			        intent.putExtra(NewsCommentFragment.PARAM_FOR_COMMENT, bundle);
			        intent.putExtra(NewsCommentFragment.PARAM_FROM_COMMENT, true);
					
					startActivity(intent);
				}else{ // 图集
										
					Intent intent = new Intent(CollectActivity.this, ImageSwitcherActivity.class);
					Bundle bundle = new Bundle();
					String jsonString = StringUtil.GetString(m.get(NewsSQLiteOpenHelper.COLLECT_PATH));
					JSONObject obj;
					String setid = "";
					String imgsum = "";
					String clientcover = "";
					String boardid = "";
					String postid = "";
					String channel = "";
					try {
						obj = new JSONObject(jsonString);
						if(obj!=null){
							setid = obj.getString("setid");
							channel = obj.getString("channel");
							imgsum = obj.getString("imgsum");
							clientcover = obj.getString("clientcover");
							boardid = obj.getString("replyBoard");
							postid = obj.getString(GetColumnsInfo.POSTID_TAG);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
					String imgTitle = m.get(NewsSQLiteOpenHelper.COLLECT_TITLE)==null?"":StringUtil.GetString(m.get(NewsSQLiteOpenHelper.COLLECT_TITLE));
					
					bundle.putString("setid", setid);
					bundle.putString("channel", channel);
					bundle.putString("imgsum", imgsum);
					bundle.putString("imgTitle", imgTitle);
					bundle.putString("clientcover", clientcover);
					bundle.putString("boardid", boardid);
					bundle.putString("postid", postid);
					bundle.putBoolean("fromCollect", true);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			}else{ // 文章
				Map<String , Object> m = collectData.get(position);
				// 参数调整，在detailPage种做判断
				String type = "attitude";
				String docId = "";
				String articleUrl = "";
				Bundle b = new Bundle();
				Object o = m.get(NewsSQLiteOpenHelper.COLLECT_OBJID);
				docId = null==o?"":o.toString();				
				o = m.get(NewsSQLiteOpenHelper.COLLECT_PATH);
				o = m.get(NewsSQLiteOpenHelper.COLLECT_TITLE);
				String title = null==o?"":o.toString();
				
				articleUrl = null==o?"":o.toString();
				b.putString(GetColumnsInfo.DOCID_TAG, docId); // 文章ID
				b.putString("position", ""+position);     // 当前位置
				b.putString(GetColumnsInfo.TID_TAG, type); // 类型  另一面 态度
				b.putString(GetColumnsInfo.URL_TAG, articleUrl);
				b.putBoolean("isCollect", true);
				b.putString(GetColumnsInfo.TITLE_TAG,title);

				Intent i = new Intent(CollectActivity.this, NewsPage.class);
				i.putExtras(b);
				startActivity(i);
			}
		}
	};

	private boolean menu_display = false;
	private LinearLayout menu_delete;
	
	private View menu_1;
	
	private void setMenu() {
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.other_page_menu, null);			
		menuWindow = new PopupWindow(layout,LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); //后两个参数是width和height
		
		menuWindow.setAnimationStyle(R.style.menuPopupAnimation);
		menu_1 = layout.findViewById(R.id.menu_tabrow_1);
		menu_delete = (LinearLayout)layout.findViewById(R.id.menu_delete);
		menu_delete.setVisibility(View.VISIBLE);
		
		menu_delete.setOnClickListener(menuDeleteListener);
	}
	@Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        menu_display = false;
    }
	/** 系统菜单定义 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if(event.getRepeatCount()>1){
			return super.onKeyDown(keyCode, event);
		}
		
		if(menu_display){
			menuWindow.dismiss();
			menu_display = false;
			return true;
		}
		if(keyCode == KeyEvent.KEYCODE_MENU){

			if(!menuWindow.isShowing()){
				menuWindow.showAtLocation(collect_layout_bg, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
				menu_display = true;
			}else{
				//如果当前已经为显示状态，则隐藏起来
				menuWindow.dismiss();
				menu_display = false;
			}
			
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	public void goBackClick(View view){
		finish();
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if(menuWindow.isShowing()){ // 点击屏幕时，隐藏菜单
			menuWindow.dismiss();
			menu_display = false;
		}
		boolean result = false;
		try {
			result = super.dispatchTouchEvent(ev);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 删除
	 */	
	private View.OnClickListener menuDeleteListener = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			if(collectData.size()==0){
				Toast.makeText(CollectActivity.this, "没有收藏数据", Toast.LENGTH_SHORT).show();
			}else{
				Intent i = new Intent();
				i.setClass(CollectActivity.this, CollectDeleteActivity.class);
				i.putExtra("type", collectType);
				startActivity(i);
			}
			menuWindow.dismiss();
			menu_display = false;
		}
	};
	
	@Override
	protected void onResume() {
		if(collectType == CollectUtil.COLLECT_PICTURES)
			setPicViewData();
		else
			setListViewData() ;
		
		super.onResume();
	}
	
	@Override
    public void onApplyTheme() {
        super.onApplyTheme();
        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        themeSettingsHelper.setTextViewColor(this, R.id.top_main_text, R.color.main_title_color);
        themeSettingsHelper.setImageViewSrc(this, R.id.top_id_image, R.drawable.netease_top);
        themeSettingsHelper.setViewBackgroud(this, R.id.top_main_bottom, R.drawable.top_background);
        themeSettingsHelper.setViewBackgroud(this, R.id.collect_title_layout, R.drawable.top_column_bg);
        themeSettingsHelper.setViewBackgroudColor(this, collect_layout_bg, R.color.main_bg_color);
        themeSettingsHelper.setTextViewColor(this, top_article, R.color.column_item_color);
        themeSettingsHelper.setTextViewColor(this, top_picture, R.color.column_item_color);
        themeSettingsHelper.setTextViewColor(this, top_comment, R.color.column_item_color);
        themeSettingsHelper.setListViewDivider(this, collectList, R.drawable.list_divider_line);
        themeSettingsHelper.setImageViewSrc(this, imageBg, R.drawable.slidebar);
        
        if (articleAdapter != null) {
            articleAdapter.notifyDataSetChanged();
        }
        if (pgridadapter != null) {
            pgridadapter.notifyDataSetChanged();
        }
        
        // 菜单夜间模式
     	themeSettingsHelper.setViewBackgroudColor(this, menu_1, R.color.menu_layout_bg_color);
        themeSettingsHelper.setViewBackgroud(this, menu_delete, R.drawable.menu_background);
        themeSettingsHelper.setTextViewColor(this, (TextView)menu_delete.getChildAt(1), R.color.menu_text_color);
      //返回夜间模式
        themeSettingsHelper.setImageViewSrc(this, R.id.go_back_common_btn, R.drawable.go_back);
        themeSettingsHelper.setTextViewColor(this, empty_text, R.color.list_title_color);
	}
}
